<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Paylog
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Paylog_Object_BalanceHandler extends Paylog_Abstract_ObjectHandler
{
	protected $object  = 'Paylog_Object_Balance';
	protected $table   = 'balance';
	protected $primary = 'id';

	public function load($id)
	{
		$obj = parent::load($id);

		$tagHand = new Paylog_Object_TagHandler;
		$obj->tagObjs = $tagHand->loadByBalanceId($id);

		return $obj;
	}

	public function loadSumMonthly($startTimeStamp, $endTimeStamp, $flow, $bookId)
	{
		$startDate = date('Y-m-d', $startTimeStamp);
		$endDate   = date('Y-m-d', $endTimeStamp);
		$flow      = intval($flow);
		$bookId    = intval($bookId);

		$sql = "SELECT sum(`price`) as `sum`, `date` FROM `%s` WHERE `date` >= '%s' AND `date` <= '%s' AND `flow` = '%u' AND `book_id` = '%u' GROUP BY `date` ORDER BY `date`";
		$sql = sprintf($sql, $this->table, $startDate, $endDate, $flow, $bookId);

		$result = $this->_query($sql);

		$sums = array();

		while ( $array = $this->db->fetchArray($result) )
		{
			$array['date'] = strtotime($array['date']);
			$sums[] = $array;
		}

		return $sums;
	}

	public function loadMonthly($startTimeStamp, $endTimeStamp, $bookId)
	{
		$startDate = date('Y-m-d', $startTimeStamp);
		$endDate   = date('Y-m-d', $endTimeStamp);
		$bookId    = intval($bookId);

		$sql = "SELECT * FROM `%s` WHERE `date` >= '%s' AND `date` <= '%s' AND `book_id` = '%u' ORDER BY `date`";
		$sql = sprintf($sql, $this->table, $startDate, $endDate, $bookId);

		$result = $this->_query($sql);

		$objs = array();
		$tagHand = new Paylog_Object_TagHandler;

		while ( $vars = $this->db->fetchArray($result) )
		{
			$obj = $this->create();
			$obj->unsetNew();
			$obj->setVars($vars);
			$obj->tagObjs = $tagHand->loadByBalanceId($vars[$this->primary]);
			$objs[] = $obj;
		}

		return $objs;
	}

	public function deleteByBookId($bookId)
	{
		$bookId = intval($bookId);
		$sql = "DELETE FROM `%s` WHERE `book_id` = '%u'";
		$sql = sprintf($sql, $this->table, $bookId);
		return $this->_query($sql);
	}
}

?>
